What is regexparam?
The regexparam npm package is a utility for matching URL patterns using regular expressions. It is designed to be lightweight and efficient, making it suitable for routing in web applications.
What are regexparam's main functionalities?
Basic Pattern Matching
This feature allows you to define URL patterns with named parameters. The `parse` function converts the pattern into a regular expression and extracts parameter names.
const { parse } = require('regexparam');
const result = parse('/user/:id');
console.log(result);
Matching URLs
This feature allows you to match a URL against a predefined pattern. The `match` function returns an object with the matched parameters if the URL matches the pattern.
const { match } = require('regexparam');
const pattern = parse('/user/:id');
const result = match('/user/123', pattern);
console.log(result);
Optional Parameters
This feature allows you to define optional parameters in your URL patterns. The `parse` function can handle patterns with optional parameters, and the `match` function will correctly match URLs with or without the optional parameter.
const { parse, match } = require('regexparam');
const pattern = parse('/user/:id?');
const result1 = match('/user/123', pattern);
const result2 = match('/user', pattern);
console.log(result1, result2);
Other packages similar to regexparam
path-to-regexp
The path-to-regexp package is a popular utility for converting URL patterns into regular expressions. It offers similar functionality to regexparam but is more feature-rich and widely used in the community. It supports advanced pattern matching, including custom parameter types and modifiers.
route-parser
The route-parser package provides a similar capability to regexparam, allowing you to define and match URL patterns. It is designed to be simple and easy to use, with a focus on readability and maintainability of route definitions.
url-pattern
The url-pattern package is another alternative for matching URL patterns. It offers a straightforward API for defining and matching patterns, with support for named parameters and wildcards. It is less feature-rich compared to path-to-regexp but provides a simpler interface.
regexparam
A tiny (308B) utility that converts route patterns into RegExp. Limited alternative to path-to-regexp
🙇
With regexparam
, you may turn a pathing string (eg, /users/:id
) into a regular expression.
An object with shape of { keys, pattern }
is returned, where pattern
is the RegExp
and keys
is an array of your parameter name(s) in the order that they appeared.
Unlike path-to-regexp
, this module does not create a keys
dictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Similarly, and most importantly, regexparam
only handles basic pathing operators:
- Static (
/foo
, /foo/bar
) - Parameter (
/:title
, /books/:title
, /books/:genre/:title
) - Parameter w/ Suffix (
/movies/:title.mp4
, /movies/:title.(mp4|mov)
) - Optional Parameters (
/:title?
, /books/:title?
, /books/:genre/:title?
) - Wildcards (
*
, /books/*
, /books/:genre/*
)
This module exposes two module definitions:
- CommonJS:
dist/regexparam.js
- ESModule:
dist/regexparam.mjs
Install
$ npm install --save regexparam
Usage
const regexparam = require('regexparam');
function exec(path, result) {
let i=0, out={};
let matches = result.pattern.exec(path);
while (i < result.keys.length) {
out[ result.keys[i] ] = matches[++i] || null;
}
return out;
}
let foo = regexparam('/books/:genre/:title?')
foo.pattern.test('/books/horror');
foo.pattern.test('/books/horror/goosebumps');
exec('/books/horror', foo);
exec('/books/horror/goosebumps', foo);
let bar = regexparam('/movies/:title.(mp4|mov)');
bar.pattern.test('/movies/narnia');
bar.pattern.test('/movies/narnia.mp3');
bar.pattern.test('/movies/narnia.mp4');
exec('/movies/narnia.mp4', bar);
let baz = regexparam('users/*');
baz.pattern.test('/users');
baz.pattern.test('/users/lukeed');
exec('/users/lukeed/repos/new', baz);
Important: When matching/testing against a generated RegExp, your path must begin with a leading slash ("/"
)!
Regular Expressions
For fine-tuned control, you may pass a RegExp
value directly to regexparam
as its only parameter.
In these situations, regexparam
does not parse nor manipulate your pattern in any way! Because of this, regexparam
has no "insight" on your route, and instead trusts your input fully. In code, this means that the return value's keys
is always equal to false
and the pattern
is identical to your input value.
This also means that you must manage and parse your own keys
~!
You may use named capture groups or traverse the matched segments manually the "old-fashioned" way:
Important: Please check your target browsers' and target Node.js runtimes' support!
const named = regexparam(/^\/posts[/](?<year>[0-9]{4})[/](?<month>[0-9]{2})[/](?<title>[^\/]+)/i);
const { groups } = named.pattern.exec('/posts/2019/05/hello-world');
console.log(groups);
const named = regexparam(/^\/posts[/]([0-9]{4})[/]([0-9]{2})[/]([^\/]+)/i);
const [url, year, month, title] = named.pattern.exec('/posts/2019/05/hello-world');
console.log(year, month, title);
API
There are two API variants:
-
When passing a String
input, the loose
parameter is able to affect the output. View API
-
When passing a RegExp
value, that must be regexparam
's only argument.
Your pattern is saved as written, so loose
is ignored entirely. View API
regexparam(str, loose)
Returns: Object
Returns a { keys, pattern }
object, where pattern
is a generated RegExp
instance and keys
is a list of extracted parameter names.
str
Type: String
The route/pathing string to convert.
Note: It does not matter if your str
begins with a /
— it will be added if missing.
loose
Type: Boolean
Default: false
Should the RegExp
match URLs that are longer than the str
pattern itself?
By default, the generated RegExp
will test that the URL begins and ends with the pattern.
const rgx = require('regexparam');
rgx('/users').pattern.test('/users/lukeed');
rgx('/users', true).pattern.test('/users/lukeed');
rgx('/users/:name').pattern.test('/users/lukeed/repos');
rgx('/users/:name', true).pattern.test('/users/lukeed/repos');
regexparam(rgx)
Returns: Object
Returns a { keys, pattern }
object, where pattern is identical to your rgx
and keys
is false
, always.
rgx
Type: RegExp
Your RegExp pattern.
Important: This pattern is used as is! No parsing or interpreting is done on your behalf.
Related
- trouter - A server-side HTTP router that extends from this module.
- matchit - Similar (650B) library, but relies on String comparison instead of
RegExp
s.
License
MIT © Luke Edwards